import axios, { type Method } from 'axios'
import { getLocalToken } from './auth'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import  router from '@/router'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000,
})

service.interceptors.request.use(
  config => {
    const token=getLocalToken()
    if(token){
      config.headers.Authorization=`Bearer ${token}`
    }
    return config
  },
  error => {
    
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.log(error.response.status)
    if(error.response.status===401){
      ElMessage.error('token失效，请重新登录')
      const store=useUserStore()
      store.setToken('')
      router.replace('/login')
    }else {
      ElMessage.error(error.response.data.message)
    }

    return Promise.reject(error)
  },
)

type Data<T> = {
  code: number
  message: string
  data: T
}

// 封装一个request 方法
const request=<T>(url:string,method:Method='GET',submitData:object)=>{
  return  service.request<T,Data<T>>({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
  })

}
export {request}
export default service
